/*
 * Creater:     柿子
 * CreateDate:  2023/05/23
 * Describe：   弹窗查询列表
 * */
import React, { Component } from 'react';
import { Modal, Button } from 'antd';
import { Util } from 'tools';
import DynamicRenderingForm from './DynamicRenderingForm';
import PublicTablePagination from './PubilcTablePagination';
// import 'pages/dynamicComponent/style/index.less';

class PublicModalQueryTable extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      queryFormData: [],
      page: 1,
      pageSize: 20,
      total: 0,
      loading: false,
      tableData: [],
      totalWidth: 0,
      columns: [],
      rowID: '',
      rowData: {},
      selectedRows: [],
      selectedRowKeys: [],
    };
  }

  componentDidMount() {
    this.props.onRef && this.props.onRef(this);
  }

  // 修改弹窗状态
  modifyVisible = (visible, params = {}) => {
    const { columns } = this.state;
    if (visible && !(columns && columns.length > 0)) {
      this.getTableColumns();
    }
    this.setState({ visible, ...params }, () => {
      visible && this.getTableData();
    })
  }

  // 获取列表表头数据
  getTableColumns = async () => {
    try {
      const { componentName } = this.props;
      if (!componentName) return;
      let data = {
        params: [{
          compontName: componentName,
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let columns = res.result?.C || [];
      if (columns && columns.length > 0) {
        this.setState({
          columns,
          totalWidth: res.totalWidth
        })
      }
      // 表单操作数据
      let queryFormData = res.result?.formData || [];
      this.setState({ queryFormData });
    } catch (error) {
      console.log(error);
    }
  }

  // 查询
  handleQuery = () => {
    this.setState({ page: 1 }, () => {
      this.getTableData();
    })
  }

  // 请求列表数据
  getTableData = async () => {
    try {
      const { queryCode, staticParams, paginationFlag, idIndex = 'key' } = this.props;
      let { queryFormData, pageSize, page } = this.state;
      if (!queryCode) return;
      let values = {};
      if (queryFormData && queryFormData.length > 0) {
        values = await this.queryFormRef.handleSave();
        if (values.error) {
          message.error('请完善必填信息');
          return;
        }
      }
      this.setState({ loading: true });
      let data = {
        params: [{
          ...staticParams,
          ...values,
        }]
      }
      if (paginationFlag === 'Y') {
        data.pagination = [{
          pageSize,
          currentPage: page
        }];
      }
      let res = await React.$asyncPost(this, queryCode, data);
      let tableData = Util.addKeyValueToDataSource(res.result?.rows || res.result?.detailInfo || res.result?.data || res.result?.Data || res?.result || [], idIndex);
      this.setState({ tableData, total: res.result?.total || res.result?.totalCount || res.result?.TotalCount || tableData.length, loading: false, rowID: '', rowData: {}, selectedRowKeys: [], selectedRows: [] });
    } catch (error) {
      console.log('error', error);
    }
  }

  // 关闭弹窗
  handleCancel = () => {
    this.modifyVisible(false);
  }

  // 分页操作
  compilePage = (page, pageSize) => {
    this.setState({ page, pageSize }, () => {
      this.getTableData();
    })
  }

  // 操作行
  onClickRowPublic = (record) => {
    const { idIndex = 'key' } = this.props;
    return {
      // 单击行选中
      onClick: () => {
        let { selectedRowKeys, selectedRows } = this.state;
        let findFlag = false;
        let start = 0;
        if (selectedRowKeys) {
          selectedRowKeys.find(function (value, key) {
            if (value === record[idIndex]) {
              findFlag = true;
              start = key;
            }
          })
        }
        if (findFlag) {
          //再次点击移除选中
          selectedRowKeys.splice(start, 1);
          selectedRows.splice(start, 1);
        } else {
          //将点击的行添加到选中
          selectedRowKeys.push(record[idIndex]);
          selectedRows.push(record);
        }
        if (this.state.rowID === '') {
          this.setState({
            rowID: record[idIndex],
            rowData: record,
            selectedRowKeys,
            selectedRows
          });
        } else {
          if (this.state.rowID !== record[idIndex]) {
            this.setState({
              rowID: record[idIndex],
              rowData: record,
              selectedRowKeys,
              selectedRows
            });
          } else {
            this.setState({
              rowID: '',
              rowData: {},
              selectedRowKeys: [],
              selectedRows: []
            });
          }
        }
      },
      onDoubleClick: () => {
        this.handleOk(record, 'doubleClick')
      }
    }
  }

  // 选中行操作
  setRowClassNamePublic = (record) => {
    const { idIndex = 'key' } = this.props;
    return record[idIndex] === this.state.rowID ? 'clickRowStyle' : '';
  }

  handleOk = (record, type) => {
    const { multipleFlag, idIndex = 'id' } = this.props;
    const { rowData, selectedRowKeys } = this.state;
    this.modifyVisible(false);
    let data = {};
    if (multipleFlag === 'Y') {
      data[idIndex + 'Arr'] = type === 'doubleClick' ? [record[idIndex]] : selectedRowKeys;
    } else {
      data = type === 'doubleClick' ? record : rowData;
    }
    this.props.handleOk && this.props.handleOk(data);
  }

  // 列表选择操作
  handleSelectedRowKeysChange = (selectedRowKeys, selectedRows) => {
    this.setState({
      selectedRows,
      selectedRowKeys,
    })
  }

  render() {
    const { title, okText, cancelText, width, isFooter, componentName, tableHeight = 400, paginationFlag, multipleFlag } = this.props;
    const { visible, queryFormData, page, total, loading, tableData, totalWidth, columns, selectedRowKeys } = this.state;
    return (
      <Modal
        visible={visible}
        width={width || '1000px'}
        title={title || '查询列表'}
        footer={isFooter !== 'N' ? (
          <div>
            <Button onClick={() => this.modifyVisible(false)}>{cancelText || '取消'}</Button>
            <Button type="primary" onClick={this.handleOk}>{okText || '确认'}</Button>
          </div>
        ) : null}
        onCancel={() => this.modifyVisible(false)}
      >
        <div className="dynamic-component table-body-height">
          <DynamicRenderingForm
            className="dynamic-component-form"
            rowData={{}}
            selectData={{}}
            formData={queryFormData && queryFormData.length > 0 ? [...queryFormData, {
              col: 2,
              typeCode: 'Button',
              type: 'primary',
              title: '查询',
              marginBottom: 12,
              onClick: this.handleQuery
            }].map((item => {
              return {
                ...item,
                onPressEnter: item.typeCode === 'Input' || item.typeCode === 'InputNumber' || item.typeCode === 'TextArea' ? this.handleQuery : ''
              }
            })) : []}
            onRef={ref => this.queryFormRef = ref}
          />
          <PublicTablePagination
            param={{
              page: paginationFlag === 'Y' ? page : false,
              total: paginationFlag === 'Y' ? total : false,
              loading,
              pageSize: '20',
              data: tableData, // 表格数据
              x: totalWidth, // 表格的宽度
              y: tableHeight,
              componentName,
              height: tableHeight + 50 + 'px',
              columns, // 表头配置
            }}
            rowSelectionPublic={multipleFlag === 'Y' ? {
              selectedRowKeys,
              onChange: this.handleSelectedRowKeysChange,
            } : null}
            compilePage={paginationFlag === 'Y' ? this.compilePage : null}
            getColumns={this.getTableColumns}
            onClickRowPublic={this.onClickRowPublic}
            setRowClassNamePublic={this.setRowClassNamePublic}
          />
        </div>
      </Modal>
    )
  }
};

export default PublicModalQueryTable;